package com.lzc.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lizhichuan
 * @description:  监听WebSocket地址
 * @date 2025/8/16 21:17
 */
@ServerEndpoint("/myWs")
@Component
@Slf4j
public class WsServerEndpoint {

    static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    //建立连接执行的操作
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
          sessionMap.put(session.getId(), session);
          log.info("websocket is open ");
    }

    //收到客户端消息执行的操作
    @OnMessage
    public String onMessage(String message) {
        log.info("收到一条消息：" + message);
        return "已收到你的消息";
    }

    //连接关闭时执行的操作
    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session.getId());
        log.info("websocket is close");
    }

    //每隔2秒主动给客户端发送心跳
    @Scheduled(fixedRate = 2000)
    public void sendMessage() throws IOException {
        for (String  key : sessionMap.keySet()) {
             Session session = sessionMap.get(key);
             session.getBasicRemote().sendText("心跳");
        }
    }

}
